#pragma once

#include "qconf.h"

namespace qio {
class EventLoop;

class Timer;

class TimerCallbacks;

using SharedTimer = std::shared_ptr<Timer>;

class Timer final : public std::enable_shared_from_this<Timer> {
  friend class TimerCallbacks;

 public:
  using TimerCallback = std::function<void(Timer *)>;
  enum Stat { kInit, kRunning, kPaused, kStopping, kStopped };

 public:
  ~Timer() QIO_NOEXCEPT;

  explicit Timer(EventLoop *loop) QIO_NOEXCEPT;

  // 启动一个定时器, timeout 为倒计时时间
  // 可以被多次调用,但是一旦 Stop 被调用,则不允许再调用 Start
  void Start(std::size_t timeout_ms) QIO_NOEXCEPT;

  // 暂停定时器
  void Pause() QIO_NOEXCEPT;

  // 取消timer,并且停止 
  void Stop() QIO_NOEXCEPT;

  // 获取定时器当前的状态
  Stat GetStat() const QIO_NOEXCEPT { return stat_; }

  // 返回指向自身的 shared_ptr
  SharedTimer ShareInstance() QIO_NOEXCEPT { return shared_from_this(); }

  Timer &OnTimeout(TimerCallback &&cb) QIO_NOEXCEPT {
    timeout_cb_ = std::forward<TimerCallback>(cb);
    return *this;
  }

  Timer &OnStop(TimerCallback &&cb) QIO_NOEXCEPT {
    stop_cb_ = std::forward<TimerCallback>(cb);
    return *this;
  }

  DISABLE_CPY_MOV(Timer)

 private:
  EventLoop *loop_;
  uv_timer_t *timer_;
  TimerCallback timeout_cb_;
  TimerCallback stop_cb_;
  Stat stat_;
};

}  // namespace qio